package com.tanhua.api;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.sso.dto.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VoiceServiceApiImpi implements VoiceServiceApi{

    @Autowired
    private MongoTemplate mongoTemplate;
    //添加语音
    @Override
    public void insert(Voice voice) {
        mongoTemplate.save(voice);
    }

    //查看语音
    @Override
    public Voice selectOne() {
        Criteria criteria = Criteria.where("seeType").is(0);
        TypedAggregation aggregation= Aggregation.newAggregation(Voice.class,Aggregation.match(criteria),Aggregation.sample(1));
        AggregationResults<Voice> aggregate = mongoTemplate.aggregate(aggregation, Voice.class);
        List<Voice> mappedResults = aggregate.getMappedResults();
        if (ObjectUtil.isEmpty(mappedResults)){
            throw new CustomException("暂无语音");
        }
        Voice voice = mappedResults.get(0);
        ObjectId id = voice.getId();
        Criteria criteria1 = Criteria.where("id").is(id);
        Update update=new Update();
        update.set("seeType",1);
        mongoTemplate.updateFirst(Query.query(criteria1),update,Voice.class);
        return voice;
    }
}
